package com.practice.dsa.interviewclassic6;

import java.util.Arrays;

/**
 * 描述
 *
 * @author yaokun.zhang
 * @version 1.0
 * @date 2022-11-08 18:41:42
 */
public class ReplaceSpaces {

    public static void main(String[] args) {
        System.out.println(replaceSpaces("Mr John Smith    ", 13));
    }

    public static String replaceSpaces(String S, int length) {
        char[] res = new char[3*length + 1];
        int i= 0;
        for(int j = 0; j < length; j ++){
            if( ' ' == S.charAt(j) ){
                res[i++] = '%';
                res[i++] = '2';
                res[i++] = '0';
            }else{
                res[i++] = S.charAt(j);
            }
        }
        return String.valueOf(res, 0, i);
    }

    public String replaceSpaces3(String S, int length) {
        char[] chs = S.toCharArray();
        int i = length-1, j = S.length()-1;
        while(i>=0){
            if(chs[i]==' '){
                chs[j--] = '0';
                chs[j--] = '2';
                chs[j--] = '%';
            }else{
                chs[j--] = chs[i];
            }
            i--;
        }
        return String.valueOf(chs,j+1, S.length()-j-1);
    }
}
